/*
 * @Author: your name
 * @Date: 2021-09-06 14:44:48
 * @LastEditTime: 2021-09-07 16:39:37
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \datadome\src\ntils\EventBus.ts
 */
/*
 * @Author: your name
 * @Date: 2021-09-06 14:44:48
 * @LastEditTime: 2021-09-06 15:15:04
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \datadome\src\ntils\EventBus.ts
 */

// 事件总线

interface DBi<T>{
    emit(type:T, value:[String, Object]):void,
    on(type, fn:Function):void,
    off(type, fn:Function):void
}
type Events = {
      list:Object 
}
class EventBus<T> implements DBi<T> {
    list:Object

    constructor() {
        this.list = {} 
    }

    on(type, fn) {
        if (!this.list[type]) {
            this.list[type] = [fn]
            return false 
        }
        this.list[type].push(fn) 
    }

    emit(type, ...arg) {
        if (!this.list[type]) return false
        this.list[type].forEach(item => {
            item.call(this, ...arg)
        }) 
    }

    off(type, fn) {
        if (!this.list[type]) return false
        if (!fn) {
            this.list[type] = []
        }
        let index = this.list[type].indexOf(fn)
        this.list[type].splice(index, 1)
    }
}

export const $ = new EventBus<Events>()
